package com.feicheng.iou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feicheng.iou.constant.SessionConstant;
import com.feicheng.iou.entity.Try;
import com.feicheng.iou.mapper.TryMapper;
import com.feicheng.iou.pojo.lifeCyclePOJO.TryAndBackviewPOJO;
import com.feicheng.iou.pojo.login.LoginReturnPOJO;
import com.feicheng.iou.pojo.login.PermissionLevelTwoPOJO;
import com.feicheng.iou.pojo.login.PermissionListPOJO;
import com.feicheng.iou.result.ResultInfo;
import com.feicheng.iou.commom.ReturnCode;
import com.feicheng.iou.constant.StatuConstant;
import com.feicheng.iou.entity.*;
import com.feicheng.iou.exception.SystemException;
import com.feicheng.iou.mapper.*;
import com.feicheng.iou.pojo.ResultTryPOJO;
import com.feicheng.iou.pojo.TryPOJO;
import com.feicheng.iou.service.TryService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.feicheng.iou.util.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianchunlei
 * @since 2021-06-28
 */
@Service
@Slf4j
@Setter
public class TryServiceImpl extends ServiceImpl<TryMapper,  Try> implements TryService {

    @Autowired
    private InterviewMapper interviewMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ResourceRecordMapper resourceRecordMapper;

    @Autowired
    private TryMapper tryMapper;

    @Autowired
    private ReservationTryMapper reservationTryMapper;

    @Autowired
    private  ReservationBackviewMapper reservationBackviewMapper;

    @Autowired
    private TryAndBackviewPOJO tryAndBackviewPOJO; //封装试听和其回访列表


    /*
     * @Author luoxin
     * @Description //处理添加试听线索的业务的service实现类
     * @Date 下午12:05 2021/6/29
     * @Param  tryPOJO 线索的POJO包含 Resource Student ResourceRecord
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo insert(TryPOJO tryPOJO) {
        log.info("TryServiceImpl类insert进入,参数为: " + tryPOJO);

        //解析POJO封装到entity
        Try tryObj = tryPOJO.getTryListen();//解析Try
        Integer studentId = tryPOJO.getStudent().getId();//解析student中的studentID
        Resource resource = tryPOJO.getResource();//解析resource
        ReservationBackview reservationBackview = new ReservationBackview();//解析ReservationBackview

        //将学生ID封装进try
        tryObj.setStudentId(studentId);
        //处理try添加，调用mapper
        int insertTryResult = tryMapper.insert(tryObj);
        //验证是否成功插入try信息
        if (insertTryResult == 0) {
            throw new SystemException(ReturnCode.TRY_INSERT_FAIL);
        }

        //修改resource的Statu为待回访
        resource.setStatu(StatuConstant.SHITINGDAIHUIFANG);
        //根据获取resource的ID修改推进状态
        int updateResourceResult = resourceMapper.updateById(resource);
        //验证验证是否成功修改线索推进状态
        if (updateResourceResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_STATU_UPDATE_FAIL);
        }

        //取到插入线索的stageId
        reservationBackview.setStageId(3);
        //取到插入的studentID
        reservationBackview.setStudentId(studentId);
        //处理reservationBackview添加，调用mapper
        int insertReservationBackview = reservationBackviewMapper.insert(reservationBackview);
        //验证是否成功插入resourceRecord
        if (insertReservationBackview == 0) {
            throw new SystemException(ReturnCode.INSERT_RESERVATION_BACKVIEW_FAIL);
        }

        log.info("TryServiceImpl类insert结束");
        return ResultInfo.success();
    }

    /*
     * @Author luoxin
     * @Description //处理修改试听线索的业务的service实现类
     * @Date 下午12:05 2021/6/29
     * @Param  tryPOJO 线索的POJO包含 Try Resource Student ResourceRecord ReservationBackview
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo update(TryPOJO tryPOJO) {
        log.info("TryServiceLmpl类进入，参数为"+tryPOJO);

        //解析POJO封装到entity
        Student student = tryPOJO.getStudent();//解析Student
        Resource resource = tryPOJO.getResource();//解析Resource
        Try tryListen = tryPOJO.getTryListen();//解析Try
        ResourceRecord resourceRecord = tryPOJO.getResourceRecord();//解析ResourceRecord
        ReservationBackview reservationBackview = tryPOJO.getReservationBackview();//解析reservationBackview

        //处理try修改，调用mapper
        int tryUpdateById = tryMapper.updateById(tryListen);
        //验证是否成功修改try信息
        if (tryUpdateById == 0) {
            throw new SystemException(ReturnCode.TRY_UPDATE_FAIL);
        }

        //处理resource修改，调用mapper
        int resourceUpdateById = resourceMapper.updateById(resource);
        //验证是否成功修改resource信息
        if (resourceUpdateById == 0) {
            throw new SystemException(ReturnCode.RESOURCE_UPDATE_FAIL);
        }

        //处理student修改，调用mapper
        int updateStudentByIdResult = studentMapper.updateById(student);
        //验证是否成功修改student信息
        if (updateStudentByIdResult == 0) {
            throw new SystemException(ReturnCode.STUDENT_UPDATE_FAIL);
        }

        //处理resourceRecord修改，调用mapper
        int resourceRecordUpdateById = resourceRecordMapper.updateById(resourceRecord);
        //验证是否成功修改resourceRecord信息
        if (resourceRecordUpdateById == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_UPDATE_FAIL);
        }

        if (reservationBackview.getDatetime() != null) {
            //处理reservationBackview修改，调用mapper
            int reservationBackviewUpdateById = reservationBackviewMapper.updateById(reservationBackview);
            //验证是否成功修改reservationBackview信息
            if (reservationBackviewUpdateById == 0) {
                throw new SystemException(ReturnCode.RESERVATIONBACKVIEW_UPDATE_FAIL);
            }
        }

        log.info("TryServiceImpl类upate结束");
        return ResultInfo.success();
    }


    /*
     * @Author luoxin
     * @Description //处理查询试听线索列表的业务的service实现类
     * @Date 下午12:05 2021/6/29
     * @Param  tryPOJO 线索的POJO包含 Try Resource Student ResourceRecord ReservationBackview
     * @return ResultInfo
     */
    @Override
    public ResultInfo listAll(TryPOJO tryPOJO, HttpServletRequest request) {
        log.info("TryServiceImpl类listAll进去，参数为" + tryPOJO);

        //定义一个放返回数据的Map
        HashMap<Object, Object> resultMap = new HashMap<>();
        //获取传入数据中的pege当前页，size每页条数得出当前页起始数据索引
        Integer pageIndex = PageUtil.getPageIndex(tryPOJO.getPage(), tryPOJO.getSize());
        //把数据索引封装到tryPOJO
        tryPOJO.setPageIndex(pageIndex);
        //检查是否拥有可分配权限，根据用户不同显示不同的数据
        LoginReturnPOJO loginReturnPOJO = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
        List<PermissionListPOJO> permissions = loginReturnPOJO.getPermissions();

        //定一个boolean的变量校验权限是否为可分配
        boolean kefenpeiFlag = false;
        for (PermissionListPOJO permissionListPOJO : permissions) {
            List<PermissionLevelTwoPOJO> permissionsTwo = permissionListPOJO.getPermissions();
            for (PermissionLevelTwoPOJO permissionLevelTwoPOJO : permissionsTwo) {
                if (permissionLevelTwoPOJO.getName().equals("可分配")) {
                    kefenpeiFlag = true;
                    break;  //如何退出两层for需调研
                }
            }
        }

        if (tryPOJO.getTryListen().getAutor() == null) {
            if (kefenpeiFlag) {
                tryPOJO.getTryListen().setAutor(null);
            } else {
                tryPOJO.getTryListen().setAutor(loginReturnPOJO.getUser().getUserId());
            }
        }

        //调用Mapper中查询条数的方法得出条数封装进tryPOJO
        tryPOJO.setTotal(tryMapper.queryTryAllCount(tryPOJO));
        //根据传入的pojo查询，结果封装到resultTryPOJOSList
        List<ResultTryPOJO> resultTryPOJOList = tryMapper.queryTryAll(tryPOJO);
        //获取pageutil里的pageinfo里的数据封装到pageinfo这个map
        Map<String, Integer> pageInfo = PageUtil.getPageInfo(tryPOJO.getPage(), tryPOJO.getSize(), tryPOJO.getTotal());

        //把pageinnfo这个map封装到resultMap中
        resultMap.put("pageInfo",pageInfo);
        //把resourcePOJOSList这个list封装到resultMap中
        resultMap.put("list",resultTryPOJOList);
        //把resultMap封装到ResultInfo中
        ResultInfo success = ResultInfo.success(resultMap);

        log.info("TryServiceImpl类listAll结束");
        return success;
    }


    /*
     * @Author luoxin
     * @Description //处理查询单个试听线索的业务的service实现类
     * @Date 下午12:05 2021/6/29
     * @Param  tryPOJO 线索的POJO包含 Try Resource Student ResourceRecord ReservationBackview
     * @return ResultInfo
     */
    @Override
    public ResultInfo selectinfo(Integer id) {
        log.info("interviewServiceImpl类selectinfo进入，进入数据为" + id);

        //定义一个放返回数据的Map
        Map<String,Object> resultMap = new HashMap<>();
        //定义一个存放studentID的map
        HashMap<String, Object> studentIdList = new HashMap<String, Object>();
        //定义一个存放resourceID的map
        HashMap<String, Object> resourceIdMap = new HashMap<String, Object>();
        //根据tryID查找，取到studentID
        Try tryListen = tryMapper.selectById(id);
        //把查到的学生ID封装到map中
        Integer studentId = tryListen.getStudentId();
        //把查到的学生ID封装到map中
        studentIdList.put("student_Id", studentId);
        //把resourceID封装到resourceIdMap中
        resourceIdMap.put("resource_Id", resourceMapper.selectByMap(studentIdList).get(0).getId());
        log.info("线索的ID是"+resourceIdMap);

        //将所有查询到的信息封装到返回信息的map中
        resultMap.put("tryListen",tryListen);
        resultMap.put("resource",resourceMapper.selectByMap(studentIdList).get(0));
        resultMap.put("student",studentMapper.selectById(studentId));
        resultMap.put("resourceRecord",resourceRecordMapper.selectByMap(resourceIdMap).get(0));

        if (reservationBackviewMapper.selectByMap(studentIdList).size() != 0){
        resultMap.put("reservationBackview",reservationBackviewMapper.selectByMap(studentIdList).get(0));
        }else{
            resultMap.put("reservationBackview", new ReservationBackview());
        }

        //把resultMap封装到ResultInfo中
        ResultInfo resultInfo = ResultInfo.success(resultMap);

        log.info("TryServiceImpl类selectinfo结束");
        return resultInfo;
    }

    /*
     * @Author luoxin
     * @Description //处理删除试听线索的业务的service实现类
     * @Date 下午12:05 2021/6/29
     * @Param  tryPOJO 线索的POJO包含 Try Resource Student ResourceRecord ReservationBackview
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo delete(TryPOJO tryPOJO) {
        log.info("interviewServiceImpl类delete进入，进入数据为" + tryPOJO);

        //解析POJO封装到entity
        Integer studentId = tryPOJO.getStudent().getId();//解析Student中Id
        Integer reservationBackviewId = tryPOJO.getReservationBackview().getId();//解析reservationBackview中Id
        Integer resourceId = tryPOJO.getResource().getId();//解析Resource中Id
        Integer tryListenId = tryPOJO.getTryListen().getId();//解析Try中Id
        Integer resourceRecordId = tryPOJO.getResourceRecord().getId();//解析ResourceRecord中Id

        //处理try删除，调用mapper
        int deleteTrybyIdResult = tryMapper.deleteById(tryListenId);
        //验证是否成功删除try信息
        if (deleteTrybyIdResult == 0) {
            throw new SystemException(ReturnCode.INTERVIEW_DELETE_FAIL);
        }

        //处理student删除，调用mapper
        int deleteStudentbyIdResult = studentMapper.deleteById(studentId);
        //验证是否成功删除student信息
        if (deleteStudentbyIdResult == 0) {
            throw new SystemException(ReturnCode.STUDENT_DELETE_FAIL);
        }

        //处理resource删除，调用mapper
        int deleteResourceByIdResult = resourceMapper.deleteById(resourceId);
        //验证是否成功删除resource信息
        if (deleteResourceByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_DELETE_FAIL);
        }

        //处理resourceRecord删除，调用mapper
        int deleteResourceRecordByIdResult = resourceRecordMapper.deleteById(resourceRecordId);
        //验证是否成功删除resourceRecord信息
        if (deleteResourceRecordByIdResult == 0) {
            throw new SystemException(ReturnCode.RESOURCERECORD_DELETE_FAIL);
        }

        //处理reservationBackview删除，调用mapper
        int deleteReservationBackviewByIdResult = reservationBackviewMapper.deleteById(reservationBackviewId);
        //验证是否成功删除reservationBackview信息
        if (deleteReservationBackviewByIdResult == 0) {
            throw new SystemException(ReturnCode.RESERVATIONBACKVIEW_DELETEE_FAIL);
        }

        log.info("TryServiceImpl类delete结束");
        return ResultInfo.success();
    }

    /*
     * @Author luoxin
     * @Description //处理试听管理分配线索的业务的service实现类
     * @Date 下午12:05 2021/6/29
     * @Param  tryPOJO 线索的POJO包含 Try Resource Student ResourceRecord ReservationBackview
     * @return ResultInfo
     */
    @Transactional
    @Override
    public ResultInfo updateAutor(TryPOJO tryPOJO) {
        log.info("TryServiceLmpl类进入，参数为"+tryPOJO);

        //解析POJO封装到entity
        Try tryListen = tryPOJO.getTryListen();//解析Try
        Integer userId = tryPOJO.getUser().getUserId();//解析User中ID

        //处理try修改，调用mapper
        tryListen.setAutor(userId);
        int updateTryByIdResult = tryMapper.updateById(tryListen);
        //验证是否成功修改try信息
        if (updateTryByIdResult == 0) {
            throw new SystemException(ReturnCode.TRY_UPDATE_FAIL);
        }

        log.info("TryServiceImpl类updateAutor结束");
        return ResultInfo.success();
    }

    @Override
    public ResultInfo abandonTry(TryPOJO tryPOJO) {
        log.info("TryServiceImpl类abandon进入");

        //解析POJO封装到entity
        Resource resource = tryPOJO.getResource();//解析Resource

        //修改线索推进状态为已放弃
        resource.setStatu(StatuConstant.YIFANGQI);
        //处理resource修改，调用mapper
        int abandonResourceResult = resourceMapper.updateById(resource);
        //验证是否成功修改resource信息
        if (abandonResourceResult == 0) {
            throw new SystemException(ReturnCode.RESOURCE_UPDATE_FAIL);
        }

        log.info("TryServiceImpl类abandon结束");
        return ResultInfo.success();
    }


    /**
     * @Author wuweinan
     * @Description 根据StudentId查询试听信息
     * @Date 2021-7-1 18:11
     * @param studentId
     * @return void
     */
    @Override
    public ResultInfo selectTryByStudentId(Integer studentId) {
        log.info("TryServiceImpl的selectTryByStudentId进入");

        //根据学生Id查询试听信息
        QueryWrapper<Try> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        Try try1 = tryMapper.selectOne(queryWrapper);

       //封装信息
        tryAndBackviewPOJO.setTry(try1);

        log.info("TryServiceImpl的selectTryByStudentId返回");
        return ResultInfo.success(try1);
    }
}
